import asyncio
from os.path import exists

import requests
import time
import aiohttp
import os

path = 'D:\webDownload\spiderData\HeroImg'


class WzHeroImgSpider:
    hero_url = 'https://pvp.qq.com/web201605/js/herolist.json'
    skin_url = 'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{}/{}-bigskin-{}.jpg'

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',

    }

    def __init__(self):
        pass

    async def get_hero(self):
        async with aiohttp.ClientSession() as client:
            resp = await client.get(self.hero_url, headers=self.headers)
            info = await resp.json(content_type=None)
            task_list = list()
            for i in info:
                e_name = i['ename']
                c_name = i['cname']
                obj = self.get_skinImg(client,e_name, c_name)
                task = asyncio.create_task(obj)
                task_list.append(task)
            await asyncio.wait(task_list)


    async def get_skinImg(self, client, e_name, c_name):
        for num in range(20):
            resp = await client.get(self.skin_url.format(e_name, e_name,num), headers=self.headers)
            if resp.status == 200:
                if not exists(path):
                    os.mkdir(path)

                img_content = await resp.read()
                with open(path + f'/{c_name}_{num}.jpg', 'wb') as f:
                    f.write(img_content)
                    print('下载成功', f'/{c_name}_{num}.jpg')


if __name__ == '__main__':
    w = WzHeroImgSpider()
    asyncio.run(w.get_hero())
